<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG智能文件助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .chat-container {
            width: 90%;
            max-width: 1200px;
            height: 90vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            overflow: hidden;
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #e9ecef;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            background: #343a40;
            color: white;
        }

        .sidebar-header h3 {
            font-size: 18px;
            margin-bottom: 5px;
        }

        .sidebar-header p {
            font-size: 14px;
            opacity: 0.8;
        }

        .sidebar-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .stats-section, .models-section {
            margin-bottom: 20px;
        }

        .stats-section h4, .models-section h4 {
            font-size: 14px;
            color: #495057;
            margin-bottom: 10px;
        }

        .stat-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e9ecef;
            font-size: 13px;
        }

        .model-select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 13px;
        }

        .sidebar-actions {
            padding: 20px;
            border-top: 1px solid #e9ecef;
        }

        .btn {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            margin-bottom: 8px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .main-chat {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            background: white;
        }

        .chat-header h2 {
            color: #343a40;
            font-size: 24px;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            margin: 0 10px;
        }

        .user .message-avatar {
            background: #007bff;
            color: white;
        }

        .assistant .message-avatar {
            background: #28a745;
            color: white;
        }

        .message-content {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 18px;
            line-height: 1.4;
            position: relative;
        }

        .user .message-content {
            background: #007bff;
            color: white;
            margin-right: 0;
        }

        .assistant .message-content {
            background: white;
            color: #343a40;
            border: 1px solid #e9ecef;
        }

        .message-time {
            font-size: 12px;
            opacity: 0.6;
            margin-top: 5px;
        }

        .message-sources {
            margin-top: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .source-title {
            font-size: 12px;
            font-weight: bold;
            color: #495057;
            margin-bottom: 8px;
        }

        .source-item {
            font-size: 11px;
            padding: 4px 0;
            border-bottom: 1px solid #dee2e6;
        }

        .source-item:last-child {
            border-bottom: none;
        }

        .source-name {
            font-weight: bold;
            color: #007bff;
        }

        .source-score {
            color: #28a745;
            font-weight: bold;
        }

        .chat-input {
            padding: 20px;
            border-top: 1px solid #e9ecef;
            background: white;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        .message-input {
            flex: 1;
            padding: 15px;
            border: 1px solid #ced4da;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
        }

        .send-btn {
            padding: 15px 25px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .send-btn:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }

        .send-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            display: flex;
            align-items: center;
            color: #6c757d;
            font-style: italic;
        }

        .loading::after {
            content: '';
            width: 20px;
            height: 20px;
            margin-left: 10px;
            border: 2px solid #f3f3f3;
            border-top: 2px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .typing-indicator {
            padding: 10px 20px;
            background: #e9ecef;
            border-radius: 18px;
            color: #6c757d;
            font-style: italic;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 0.6; }
            50% { opacity: 1; }
        }

        @media (max-width: 768px) {
            .chat-container {
                width: 95%;
                height: 95vh;
            }
            
            .sidebar {
                display: none;
            }
            
            .message-content {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h3>🤖 RAG助手</h3>
                <p>基于您的文件内容进行智能问答</p>
            </div>
            
            <div class="sidebar-content">
                <div class="stats-section">
                    <h4>📊 系统状态</h4>
                    <div class="stat-item">
                        <span>对话消息:</span>
                        <span id="chat-count">0</span>
                    </div>
                    <div class="stat-item">
                        <span>文件索引:</span>
                        <span id="file-count">0</span>
                    </div>
                    <div class="stat-item">
                        <span>当前模型:</span>
                        <span id="current-model">加载中...</span>
                    </div>
                </div>
                
                <div class="models-section">
                    <h4>🔄 切换模型</h4>
                    <select id="model-select" class="model-select">
                        <option value="">加载中...</option>
                    </select>
                </div>
            </div>
            
            <div class="sidebar-actions">
                <button class="btn btn-primary" onclick="loadHistory()">📝 查看历史</button>
                <button class="btn btn-secondary" onclick="clearHistory()">🗑️ 清空历史</button>
                <button class="btn btn-primary" onclick="showFileSearch()">🔍 文件搜索</button>
            </div>
        </div>
        
        <!-- 主聊天区域 -->
        <div class="main-chat">
            <div class="chat-header">
                <h2>💬 智能文件助手</h2>
            </div>
            
            <div class="chat-messages" id="chat-messages">
                <div class="message assistant">
                    <div class="message-avatar">🤖</div>
                    <div class="message-content">
                        <div>您好！我是您的智能文件助手。</div>
                        <div>我可以帮您：</div>
                        <ul style="margin: 10px 0; padding-left: 20px;">
                            <li>搜索和查找文件</li>
                            <li>回答关于文件内容的问题</li>
                            <li>分析和总结文档信息</li>
                            <li>提供准确的文件引用</li>
                        </ul>
                        <div>请输入您的问题开始对话！</div>
                        <div class="message-time">系统消息</div>
                    </div>
                </div>
            </div>
            
            <div class="chat-input">
                <div class="input-group">
                    <input 
                        type="text" 
                        id="message-input" 
                        class="message-input" 
                        placeholder="输入您的问题..." 
                        onkeypress="handleKeyPress(event)"
                    >
                    <button id="send-btn" class="send-btn" onclick="sendMessage()">
                        发送
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let isLoading = false;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadModels();
            loadStats();
            
            // 定期更新统计信息
            setInterval(loadStats, 30000);
        });

        // 处理键盘事件
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            
            if (!message || isLoading) return;
            
            // 显示用户消息
            appendMessage('user', message);
            input.value = '';
            
            // 显示加载状态
            isLoading = true;
            updateSendButton();
            showTypingIndicator();
            
            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message: message })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    appendMessage('assistant', data.response, data.sources);
                } else {
                    appendMessage('assistant', '抱歉，处理您的请求时出现错误: ' + data.error);
                }
                
            } catch (error) {
                appendMessage('assistant', '网络错误，请检查连接后重试。');
                console.error('Error:', error);
            } finally {
                isLoading = false;
                updateSendButton();
                hideTypingIndicator();
                loadStats(); // 更新统计信息
            }
        }

        // 添加消息到聊天区域
        function appendMessage(role, content, sources = null) {
            const messagesContainer = document.getElementById('chat-messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            
            const avatar = role === 'user' ? '👤' : '🤖';
            const time = new Date().toLocaleTimeString();
            
            let sourcesHtml = '';
            if (sources && sources.length > 0) {
                sourcesHtml = `
                    <div class="message-sources">
                        <div class="source-title">📚 参考文件 (${sources.length}个):</div>
                        ${sources.map(source => `
                            <div class="source-item">
                                <div class="source-name">${source.file_name}</div>
                                <div style="color: #6c757d; font-size: 10px;">${source.file_path}</div>
                                <div>相似度: <span class="source-score">${source.similarity_score}</span></div>
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            
            messageDiv.innerHTML = `
                <div class="message-avatar">${avatar}</div>
                <div class="message-content">
                    <div>${content.replace(/\n/g, '<br>')}</div>
                    ${sourcesHtml}
                    <div class="message-time">${time}</div>
                </div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 显示输入指示器
        function showTypingIndicator() {
            const messagesContainer = document.getElementById('chat-messages');
            const indicator = document.createElement('div');
            indicator.id = 'typing-indicator';
            indicator.className = 'message assistant';
            indicator.innerHTML = `
                <div class="message-avatar">🤖</div>
                <div class="typing-indicator">正在思考中...</div>
            `;
            messagesContainer.appendChild(indicator);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            const indicator = document.getElementById('typing-indicator');
            if (indicator) {
                indicator.remove();
            }
        }

        // 更新发送按钮状态
        function updateSendButton() {
            const sendBtn = document.getElementById('send-btn');
            sendBtn.disabled = isLoading;
            sendBtn.textContent = isLoading ? '发送中...' : '发送';
        }

        // 加载模型列表
        async function loadModels() {
            try {
                const response = await fetch('/api/models');
                const data = await response.json();
                
                if (data.success) {
                    const select = document.getElementById('model-select');
                    select.innerHTML = '';
                    
                    data.models.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model;
                        option.textContent = model;
                        option.selected = model === data.current_model;
                        select.appendChild(option);
                    });
                    
                    // 绑定切换事件
                    select.addEventListener('change', switchModel);
                }
            } catch (error) {
                console.error('Failed to load models:', error);
            }
        }

        // 切换模型
        async function switchModel() {
            const select = document.getElementById('model-select');
            const modelName = select.value;
            
            if (!modelName) return;
            
            try {
                const response = await fetch('/api/model', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ model: modelName })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('current-model').textContent = data.current_model;
                    appendMessage('assistant', `已切换到模型: ${data.current_model}`);
                }
            } catch (error) {
                console.error('Failed to switch model:', error);
            }
        }

        // 加载统计信息
        async function loadStats() {
            try {
                const response = await fetch('/api/stats');
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('chat-count').textContent = data.stats.chat_messages;
                    document.getElementById('file-count').textContent = data.stats.milvus_entities.toLocaleString();
                    document.getElementById('current-model').textContent = data.stats.current_model;
                }
            } catch (error) {
                console.error('Failed to load stats:', error);
            }
        }

        // 加载历史记录
        async function loadHistory() {
            try {
                const response = await fetch('/api/history');
                const data = await response.json();
                
                if (data.success) {
                    if (data.history.length === 0) {
                        alert('暂无对话历史');
                        return;
                    }
                    
                    // 清空当前消息
                    document.getElementById('chat-messages').innerHTML = '';
                    
                    // 显示历史消息
                    data.history.forEach(msg => {
                        appendMessage(msg.role, msg.content, msg.sources);
                    });
                }
            } catch (error) {
                console.error('Failed to load history:', error);
                alert('加载历史记录失败');
            }
        }

        // 清空历史记录
        async function clearHistory() {
            if (!confirm('确定要清空对话历史吗？')) return;
            
            try {
                const response = await fetch('/api/history', {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('chat-messages').innerHTML = '';
                    appendMessage('assistant', '对话历史已清空');
                    loadStats();
                }
            } catch (error) {
                console.error('Failed to clear history:', error);
                alert('清空历史记录失败');
            }
        }

        // 显示文件搜索对话框
        function showFileSearch() {
            const query = prompt('输入搜索关键词:');
            if (!query) return;
            
            // 发送搜索消息
            document.getElementById('message-input').value = `搜索文件: ${query}`;
            sendMessage();
        }
    </script>
</body>
</html>